package net.zigin.nhi.waste.view.ble;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.gyf.immersionbar.ImmersionBar;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.BleDeviceAdapter;
import net.zigin.nhi.waste.constants.Constants;

import java.util.ArrayList;
import java.util.List;

import io.paperdb.Paper;
import io.reactivex.functions.Consumer;

/**
 * 搜索连接蓝牙界面
 */
public class BleSearchActivity extends AppCompatActivity implements View.OnClickListener {

    private RelativeLayout mCurrentLayout;
    private TextView mBleName;
    private Button mDisconnect;
    private Button mStart;
    private Button mStop;
    private TextView mDevNum;
    private RecyclerView mRvBle;
    private BleDeviceAdapter mAdapter;//蓝牙设备列表适配器
    private List<BleDevice> list;//数据来源

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble_search);
        initView();

        if (Build.VERSION.SDK_INT >= 23) {//6.0或6.0以上
            //动态权限申请
            permissionsRequest();
        }
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mCurrentLayout = findViewById(R.id.current_layout);
        mBleName = findViewById(R.id.ble_name);
        mDisconnect = findViewById(R.id.disconnect);
        mStart = findViewById(R.id.start);
        mStop = findViewById(R.id.stop);
        mDevNum = findViewById(R.id.dev_num);
        mRvBle = findViewById(R.id.rv_ble);

        mStart.setOnClickListener(this);
        mStop.setOnClickListener(this);
    }

    @SuppressLint("StringFormatMatches")
    @Override
    protected void onResume() {
        super.onResume();

        list = new ArrayList<>();
        mAdapter = new BleDeviceAdapter(list);
        mRvBle.setLayoutManager(new LinearLayoutManager(this));
        mRvBle.setAdapter(mAdapter);

        initData();
    }

    private void initData() {
        if (Constants.BLEDEVICE != null) {
            mCurrentLayout.setVisibility(View.VISIBLE);
            mBleName.setText(Constants.BLEDEVICE.getName());

            mDisconnect.setOnClickListener(v -> {
                if (BleManager.getInstance().isConnected(Constants.BLEDEVICE)) {
                    BleManager.getInstance().disconnect(Constants.BLEDEVICE);
                    mCurrentLayout.setVisibility(View.GONE);
                }
            });
        } else {
            mCurrentLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 动态权限申请，获取蓝牙权限必须打开位置权限
     */
    @SuppressLint("CheckResult")
    private void permissionsRequest() {
        //权限请求
        RxPermissions rxPermissions = new RxPermissions(this);//实例化这个权限请求框架，否则会报错
        rxPermissions.requestEach(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                    }
                });
    }

    @SuppressLint({"StringFormatMatches", "NonConstantResourceId", "NotifyDataSetChanged"})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start:  //开始扫描
                try {
                    if (BleManager.getInstance().isSupportBle()) {//是否支持蓝牙
                        if (BleManager.getInstance().isBlueEnable()) {//打开
                            if (!isGpsEnable(this)) {
                                Toast.makeText(this, "扫描蓝牙前请先打开GPS！", Toast.LENGTH_LONG).show();
                                //跳转到gps设置页
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivityForResult(intent, 0);
                            } else {
                                if (mAdapter != null) {//当适配器不为空时，这时就说明已经有数据了，所以清除列表数据，再进行扫描
                                    list.clear();
                                    mAdapter.notifyDataSetChanged();
                                }
                                //开始扫描周围的蓝牙设备
                                BleManager.getInstance().scan(new BleScanCallback() {
                                    @Override
                                    public void onScanFinished(List<BleDevice> scanResultList) {
                                        //本次扫描时段内所有被扫描且过滤后的设备集合。它会回到主线程，相当于onScanning设备之和
                                    }

                                    @Override
                                    public void onScanStarted(boolean success) {
                                        //会回到主线程，参数表示本次扫描动作是否开启成功。由于蓝牙没有打开，上一次扫描没有结束等原因，会造成扫描开启失败
                                        list.clear();
                                        Resources resources = getResources();
                                        mDevNum.setText(String.format(resources.getString(R.string.scanned), 0));
                                        mAdapter.notifyDataSetChanged();
                                    }

                                    @Override
                                    public void onScanning(BleDevice bleDevice) {
                                        //扫描过程中的所有过滤后的结果回调。出现的设备是经过扫描过滤规则过滤后的设备。
                                        if (bleDevice.getName() != null && !bleDevice.getName().equals("")) {
                                            list.add(bleDevice);
                                            mAdapter.notifyDataSetChanged();
                                            Resources resources = getResources();
                                            mDevNum.setText(String.format(resources.getString(R.string.scanned), list.size()));
                                        }
                                    }
                                });
                            }
                        } else {//未打开
                            Toast.makeText(this, "请打开蓝牙！", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "你的设备不支持蓝牙", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.stop:   //停止扫描
                BleManager.getInstance().cancelScan();
                break;
        }
    }

    /**
     * 检测gbs是否可用，位置权限是否开启
     *
     * @param context
     * @return
     */
    private boolean isGpsEnable(final Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }
}